from pms.common.views import PostFormula
from info.models import Mail
from department.utils import assert_department_permissions
from department.utils.member import assert_member_of as assert_department_member_of
from project.utils.member import assert_member_of as assert_project_member_of
from project.utils.permission import assert_project_permissions
from user.utils.permission import assert_system_permissions
from info.utils.mail import mail_view


class API(PostFormula):

    def handle(self, req):
        mail = Mail.objects.get(id=req['id'])
        if mail.uid != self.user:  # 当前用户不为发件人时才要验证权限
            if mail.did is not None:
                assert_department_member_of(self.user, mail.did)
                assert_department_permissions(self.user.id, mail.did.id, [5])
            elif mail.pid is not None:
                assert_project_member_of(self.user, mail.pid)
                assert_project_permissions(mail.pid.id, self.user.id, [7])
            else:
                assert_system_permissions(self.user.id, [16])
        return self.success_respond(mail_view(mail))
